package mat;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.Logger;

/**
 * Writes into a .bak file, renames it to the original name on close().
 * 
 * @author ex71417
 *
 */
public class SafeMultiProtocolFileOutputStream extends OutputStream
{
	private MultiProtocolFile mpf;
	private OutputStream out;
	private MultiProtocolFile bak;
	private Logger log;
	
	public SafeMultiProtocolFileOutputStream(MultiProtocolFile mpf) throws IOException
	{
		this(mpf, 8192);
	}
	
	public SafeMultiProtocolFileOutputStream(MultiProtocolFile mpf, int bufferSize) throws IOException
	{
		this.log = Logger.getLogger(this.getClass());
		this.mpf = mpf;
		this.bak = new MultiProtocolFile(mpf.getPath() + ".bak");
		
		if (mpf.exists())
		{
			// delete results file, write to *.bak file. Rename afterwards.
//			log.info("Deleting " + mpf.getPath());
			mpf.delete();
		}
//		log.info("Writing result to " + bak.getPath());		

		out = new BufferedOutputStream(bak.getOutputStream(), bufferSize);
	}
	
	@Override
	public void write(int b) throws IOException
	{
		out.write(b);	
	}	

	@Override
	public void write(byte[] b, int off, int len) throws IOException
	{
		out.write(b, off, len);
	}

	@Override
	public void write(byte[] b) throws IOException
	{
		out.write(b);
	}

	@Override
	public void flush() throws IOException
	{
		out.flush();
	}

	@Override
	public void close() throws IOException
	{
		out.close();
		
//		log.info("Renaming " + bak.getPath() + " to " + mpf.getPath());		
		if (!bak.renameTo(mpf))
			throw new IOException("Failed to rename " + bak.getPath() + " to " + mpf.getPath());
	}
}


